"""
This file is part of GlToolkit project https://code.google.com/p/gltoolkit/

Copyright (C) 2009-2010 Synble Ltd.
All rights reserved.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
"""
import urllib
import urllib2
import base64
import itertools, mimetools, mimetypes

class MultiPartForm(object):
    """Accumulate the data to be used when posting a form."""

    def __init__(self):
        self.formFields = []
        self.files = []
        self.boundary = mimetools.choose_boundary()

    def getContentType(self):
        return 'multipart/form-data; boundary=%s' % self.boundary

    def addField(self, name, value):
        """Add a form field to the form data."""
        self.formFields.append((name, value))

    def addFile(self, fieldname, filename, fileHandle, mimetype=None):
        body = fileHandle.read()
        if mimetype is None:
            mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'

        self.files.append((fieldname, filename, mimetype, body))

    def __str__(self):
        parts = []
        partBoundary = '--' + self.boundary

        # Add the form fields

        parts.extend([ partBoundary,'Content-Disposition: form-data; name="%s"' % name,
        '', value,] for name, value in self.formFields)

        # Add the files to upload
        # Amazon S3 expects file data to be 'Content-Disposition:
        # form-data' instead of "file"

        parts.extend([ partBoundary,'Content-Disposition: form-data; name="%s"; filename="%s"' % \
        (fieldName, filename),'Content-Type: %s' % contentType,'',body,]
        for fieldName, filename, contentType, body in self.files)

        # Flatten the list and add closing boundary marker,
        # then return \r\n separated data
        flattened = list(itertools.chain(*parts))
        flattened.append('--' + self.boundary + '--')
        flattened.append('')
        return '\r\n'.join(flattened)


class GLApi:
    def setUsername(self, username):
        self.username = username
        
    def setPassword(self, password):
        self.password = password
        
    def uploadFile(self, file, product, language, component):
        params = urllib.urlencode({'product': product,
                                   'language': language,
                                   'component': component})

        f = open(file)
        form = MultiPartForm()
        form.addFile('file', file, f)
     
        url = 'http://www.getlocalization.com/ajax/uploadLanguageFile/?%s' % params;

        if language=='master':
            url = 'http://www.getlocalization.com/ajax/commitStrings/?%s' % params;

        req = urllib2.Request(url)
        base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
        authheader =  "Basic %s" % base64string
        req.add_header("Content-Type", form.getContentType());
        req.add_header("Authorization", authheader)
        req.add_data(str(form))
        urlObj = urllib2.urlopen(req)

        print urlObj.read()
        pass

    def getFile(self, product, language, component):
        params = urllib.urlencode({'product': product,
                                   'language': language,
                                   'component': component})

        url = 'http://www.getlocalization.com/component/export/?%s' % params
        req = urllib2.Request(url)
        base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
        authheader =  "Basic %s" % base64string
        req.add_header("Authorization", authheader)
        
        urlObj = urllib2.urlopen(req)
        response = urlObj.read()

        print response

